package top.aiprogram.common.Interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by HP on 2018/10/15.
 * 创建session的拦截器,对登录的用户的session进行判断,如果session中没有
 * 用户信息,返回到登录页面,这实际上就是对发送到mvc的请求进行拦截.
 * 拦截器需要实现那个HandlerInterceptor接口
 */

public class SessionInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //当判断访问路径中是否存在某个字符串的时候,采用获取URI的方式进行.
        String requestURI = httpServletRequest.getRequestURI();
        if ((requestURI.indexOf("login")>=0)||requestURI.indexOf("signattend")>=0||requestURI.indexOf("error")>=0||(requestURI.indexOf("Attend")>=0)){
            //如果含有login,就放过你,让你去请求登录页面
            return true;
        }else {
            if (httpServletRequest.getSession().getAttribute("userinfo")!=null){
                return true;
            }else {
                //跳转到登录页面
                httpServletRequest.getRequestDispatcher("/login/login").forward(httpServletRequest,httpServletResponse);
                return false;
            }
        }

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
